<template>
  <el-dialog
    :title="dialogAttr.title"
    :visible.sync="dialogShow"
    width="500px"
    append-to-body
    @close="close"
    class="form-dialog"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="24" v-if="form.parentId !== 0">
          <el-form-item label="上级部门" prop="parentId">
            <el-input v-model="form.parentName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="form.deptName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number
              v-model="form.orderNum"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { rules, initForm } from "./options";
import { add, edit } from "@/api/sys/dept";

const stateObj = {
  add: {
    title: "添加部门",
    fn: add,
  },
  edit: {
    title: "编辑部门",
    fn: edit,
  },
};

export default {
  components: {},
  data() {
    return {
      dialogShow: false,
      form: initForm(),
      rules,
      dialogAttr: {},
    };
  },
  methods: {
    open(type, row = {}) {
      this.dialogAttr = stateObj[type];
      this.form = Object.assign({}, initForm(), row);
      this.dialogShow = true;
    },
    // 提交按钮
    submitForm: function() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let row = { ...this.form };
          if (row.id) row.deptId = row.id;
          this.dialogAttr.fn(row).then(() => {
            this.$message.success("新增成功");
            this.dialogShow = false;
            this.$emit("submit_success");
          });
        }
      });
    },
    close() {
      this.dialogShow = false;
      this.form = initForm();
    },
  },
};
</script>

<style scoped lang="scss">
.form-dialog {
  &::v-deep .el-input-number {
    width: 100%;
  }
}
</style>
